//
//  AECommunityDetailViewController.m
//  AESOLAR_IOS
//
//  Created by Bin Tang on 2024/10/20.
//  Copyright © 2024 Mr.Wang. All rights reserved.
//

#import "AECommunityDetailViewController.h"
#import "AECommunityDetailViewModel.h"
#import "EDSCommentInputView.h"
#import "AECommunityDetailViewCell.h"
#import "AE_Solar-Swift.h"
#import "AECommunityDetailHeaderView.h"
#import "AEShareInfoView.h" // 分享

@interface AECommunityDetailViewController () <TYZTouchTableViewDelegate>

@property (nonatomic, strong) AECommunityDetailViewModel *viewModel;

/// 分享按钮
@property (nonatomic, strong) TYZImageTitleButton *btnShare;

@property (nonatomic, strong) AECommunityDetailHeaderView *headerView;

@property (nonatomic, strong) EDSCommentInputView *inputView;

@property (nonatomic, strong) AEShareInfoView *shareView;



@end

@implementation AECommunityDetailViewController

- (void)dealloc
{
    debugMethod();
}

- (void)initWithVar
{
    [super initWithVar];
    
}

- (void)initWithViewModel
{
    _viewModel = [[AECommunityDetailViewModel alloc] init];
    _viewModel.newsInfoModel = self.newsInfoModel;
    [_viewModel setupData];
}

- (void)initWithNavBar
{
    [super initWithNavBar];
    
    [self initWithBackButton];
    
    self.navigationItem.title = self.viewModel.title;
    
    [self initWithBtnShare];
}

- (void)initWithSubView
{
    [super initWithSubView];
    
    
    
    [self hiddenFooterView:YES];
    
    [self.baseTableView registerClass:[AECommunityDetailViewCell class] forCellReuseIdentifier:[AECommunityDetailViewCell className]];
    self.baseTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self hiddenFooterView:YES];
//    self.baseTableView.height = self.baseTableView.height - kEDSCommentInputViewHeight;
    
    self.baseTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.baseTableView.showsVerticalScrollIndicator = NO;
    self.baseTableView.showsHorizontalScrollIndicator = NO;
    self.baseTableView.touchDelegate = self;
    self.baseTableView.backgroundColor = kWhiteColor;
    
//    [self initWithInputView];
    
//    [self initWithShareView];
    
//    RAC(self.viewModel, commentContent) = self.inputView.textView.rac_textSignal;

    [self initWithDetailHeaderView];
    
    
//    @weakify(self);
//    [self.noDataView setViewBlock:^(id data) {
//        @strongify(self);
//        [self beginRefreshing];
//    }];
//    [self requestWithIndustryPostDetail];
    [self doRefreshData];
    
    [self requestWithNewsBrowse];
    
    [self initWithShareView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillShowKeyboard:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillHideKeyboard:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

/// 分享
- (void)initWithShareView {
    if (!_shareView) {
        float height = 226 + IPHONEX_BOTTOM_SPACE;
        CGRect frame = CGRectMake(0, kScreenH - height , kScreenW, height);
        _shareView = [[AEShareInfoView alloc] initWithFrame:frame];
    }
}


/// 分享
- (void)initWithBtnShare {
    if (!_btnShare) {
        UIImage *image = [UIImage imageNamed:@"ic_main_share"];
        UIFont *font = [UIFont systemFontOfSize:12 weight:UIFontWeightBold];
        NSString *title = [AEStringExten localizedValueWithKey:@"分享"];
        float width = [title widthForFont:font] + 2 + 5 + 16 + image.size.width;
        CGRect frame = CGRectMake(0, 0, width, 30);
        _btnShare = [TYZImageTitleButton createWithImageButton:nil frame:frame font:font target:self action:@selector(actionWithShare:) propertiesBlock:^(TYZImageTitleButton * _Nonnull button) {
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:kThemeColor forState:UIControlStateNormal];
            [button setImage:image forState:UIControlStateNormal];
            [button layoutButtonWithEdgeInsetsStyle:TYZButtonEdgeInsetsStyleLeft imageTitleSpace:4];
            button.backgroundColor = [UIColor colorWithHexString:@"#EEEEEE"];
            button.layer.cornerRadius = frame.size.height * 0.5;
            button.layer.masksToBounds = YES;
        }];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:_btnShare];
        self.navigationItem.rightBarButtonItem = rightItem;
    }
}

- (void)initWithDetailHeaderView {
    if (!_headerView) {
        CGRect frame = CGRectMake(0, 0, kScreenW, self.viewModel.newsInfoModel.headerHeight);
        _headerView = [[AECommunityDetailHeaderView alloc] initWithFrame:frame];
        self.baseTableView.tableHeaderView = _headerView;
        
        @weakify(self);
        self.headerView.touchPraiseBlock = ^{
            @strongify(self);
            [self actionWithPraise: self.viewModel.newsInfoModel];
        };
    }
    
    [self.headerView updateWithViewData:self.viewModel];
}

- (void)initWithInputView
{
    if (!_inputView)
    {
        CGRect frame = CGRectMake(0, self.baseTableView.bottom, kScreenWidth, kEDSCommentInputViewHeight);
        _inputView = [[EDSCommentInputView alloc] initWithFrame:frame];
        [self.view addSubview:_inputView];
        
        @weakify(self);
        _inputView.sendCommentContentBlock = ^(NSString * _Nonnull msg) {
            @strongify(self);
            [self actionWithSend:msg];
        };
        _inputView.touchTextEditBlock = ^(BOOL isStart) {
            @strongify(self);
            if (!isStart)
            {
                self.inputView.placeholder = @"来说两句评论一下吧~";
                self.viewModel.commentType = 1;
            }
        };
        RAC(self.viewModel, commentContent) = self.inputView.textView.rac_textSignal;
    }
}

/// 显示分享弹窗
- (void)showShareVC:(AENewsInfoModel *)model {
    @weakify(self);
    NSString *shareUrl = [NSString stringWithFormat:@"%@photovoltaic-share/news/detail.html?id=%zd", kBaseUrl, model.id];
    [_shareView showWithTitle:@"立即分享给好友" data:nil completion:^(id  _Nonnull data) {
        @strongify(self);
        NSInteger tag = [data integerValue];
        UIImage *image = [UIImage imageNamed:@"logo"];
        if (tag == 100) { // 微信
            [EDSUtility shareWithTitle:model.newsTitle desc:@"" shareUrl:shareUrl shareType:1 image:image];
        } else if (tag == 101) { // 朋友圈
            [EDSUtility shareWithTitle:model.newsTitle desc:@"" shareUrl:shareUrl shareType:2 image:image];
        }
        [self.shareView hide];
    } failed:^{
        @strongify(self);
        [self.shareView hide];
    }];
}

/// 浏览获取积分
- (void)requestWithNewsBrowse {
    [self.viewModel requestWithNewsBrowse:^(EDSRespondDataEntity * _Nonnull respond) {
            
    }];
}

/// 发送信息
/// - Parameter msg: msg description
- (void)actionWithSend:(NSString *)msg {
    
    if ([objectNull(self.viewModel.commentContent) isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"您评论的内容不能为空！"];
        return;
    }
    if (self.viewModel.isSending) {
        return;
    }
    self.viewModel.isSending = YES;
    [SVProgressHUD showWithStatus:@"发送中......"];
    @weakify(self);
    [self.viewModel requestWithAddComment:self.viewModel.commentContent completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            [SVProgressHUD showInfoWithStatus:@"您的评论发送成功！"];
            self.viewModel.isSendSuc = YES;
            self.viewModel.newsInfoModel.newsCommentsCount += 1;
            self.viewModel.commentContent = @"";
            [self.view endEditing:YES];
            [self.baseTableView reloadData];
        } else {
            [SVProgressHUD showInfoWithStatus:@"您的评论发送失败，请稍后再试！"];
        }
        self.viewModel.isSending = NO;
    }];
}

/// 分享
/// - Parameter sender: sender description
- (void)actionWithShare:(id)sender {
//    [SVProgressHUD showInfoWithStatus:@"分享"];
//    [[AEAppDelegateTool sharedInstance] requestWithSysConfig:^(EDSRespondDataEntity * _Nonnull respond) {
//        [[AEAppDelegateTool sharedInstance] showShareVC:self];
//    }];
    
    [self showShareVC: self.viewModel.newsInfoModel];
}

/// 点赞
/// - Parameter model: model description
- (void)actionWithPraise:(AENewsInfoModel *)model {
    @weakify(self);
    [SVProgressHUD showWithStatus:@"操作中..."];
    NSInteger newsId = model.id;
    NSInteger like = (model.like == YES ? 0 : 1);
    NSString *err = (like == 1 ? @"点赞失败，请稍后再试！" : @"取消点赞失败，请稍后再试！");
    NSString *suc = (like == 1 ? @"点赞成功" : @"取消点赞成功");
    [self.viewModel requestWithNewsLikeNewsId:newsId like:like completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            model.like = !model.like;
            if (model.like) {
                model.newsLikes += 1;
            } else {
                model.newsLikes -= 1;
            }
            [self.headerView updateWithViewData:self.viewModel];
            [SVProgressHUD showSuccessWithStatus:suc];
        } else {
            [SVProgressHUD showInfoWithStatus:err];
        }
    }];
}

- (void)doRefreshData {
    [super doRefreshData];
    
    [self fromServerRequestData];
}

- (void)doMoreRefreshData {
    [super doMoreRefreshData];
    
    [self fromServerRequestData];
    
}

- (void)fromServerRequestData {
    @weakify(self);
    [self.viewModel requestWithNewsComments:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        [self.baseTableView reloadData];
        [self endAllRefreshing];
    }];
}


#pragma mark - 通知
- (void)handleWillShowKeyboard:(NSNotification *)note
{
    @weakify(self);
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        @strongify(self);
        CGFloat keyboardY = [self.view convertRect:keyBoardBounds fromView:nil].origin.y;
        self.inputView.height = self.inputView.inputViewHeight;
        self.inputView.bottom = keyboardY;
        self.inputView.keyboardY = keyboardY;
    };
    
    [self keyBoardsWillShow:note animations:animation completion:^(BOOL finished, CGRect keyBoardBounds) {
        @strongify(self);
        
        if (self.viewModel.commentType == 2)
        {
//            self.inputView.placeholder = [NSString stringWithFormat:@"回复 %@", objectNull(self.viewModel.selReplyCommentModel.username)];
        }
        else
        {
            self.inputView.placeholder = @"来说两句评论一下吧~";
        }
    }];
}

- (void)handleWillHideKeyboard:(NSNotification *)note
{
    @weakify(self);
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        @strongify(self);
        if (self.viewModel.isSendSuc)
        {
            [self.inputView resetHeight];
            self.viewModel.isSendSuc = NO;
        }
        
        CGFloat height = kScreenHeight - NAVBAR_HEIGHT_STATUS - self.inputView.inputViewHeight - IPHONEX_BOTTOM_SPACE;
        self.baseTableView.height = height;
        self.inputView.height = self.inputView.inputViewHeight +IPHONEX_BOTTOM_SPACE;
        self.inputView.top = self.baseTableView.bottom;
        self.inputView.keyboardY = 0;
    };
    [self keyBoardsWillHide:note animations:animation completion:^(BOOL finished) {
        
    }];
}

/// 评论点赞
/// - Parameter model: model description
- (void)actionWithCommentPraise:(AENewsCommentsModel *)model indexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    [SVProgressHUD showWithStatus:@"操作中..."];
    NSInteger commentId = model.id;
    NSInteger like = (model.like == YES ? 0 : 1);
    NSString *err = (like == 1 ? @"点赞失败，请稍后再试！" : @"取消点赞失败，请稍后再试！");
    NSString *suc = (like == 1 ? @"点赞成功" : @"取消点赞成功");
    [self.viewModel requestWithNewsLikeCommentId:commentId like:like completion:^(EDSRespondDataEntity * _Nonnull respond) {
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            model.like = !model.like;
            if (model.like) {
                model.commentsLikes += 1;
            } else {
                model.commentsLikes -= 1;
            }
            [self.baseTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [SVProgressHUD showSuccessWithStatus:suc];
        } else {
            [SVProgressHUD showInfoWithStatus:err];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = self.viewModel.newsInfoModel.comments.count;
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AECommunityCommentModel *model = [self.viewModel.newsInfoModel.comments objectOrNilAtIndex:indexPath.row];
    return model.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    AECommunityDetailViewCell *cell = [AECommunityDetailViewCell cellForTableView:tableView indexPath:indexPath];
    AENewsCommentsModel *model = [self.viewModel.newsInfoModel.comments objectOrNilAtIndex:indexPath.row];
    [cell updateCellData:model];
    if (indexPath.row == self.viewModel.newsInfoModel.comments.count - 1) {
        cell.bottomLine.hidden = YES;
    } else {
        cell.bottomLine.hidden = NO;
    }
    cell.touchCommentPraiseBlock = ^{
        @strongify(self);
        [self actionWithCommentPraise:model indexPath:indexPath];
    };
    return cell;
}


#pragma mark - TYZTouchTableViewDelegate
- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    [self.view endEditing:YES];
}

- (void)tableView:(UITableView *)tableView touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)tableView:(UITableView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)tableView:(UITableView *)tableView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
